package filmring

class RatingController {

    def index = { }

    def rate = {
        //Updates or creates a rating object for the user and movie
        System.out.println("User Id "+params.userId+" Movie "+params.movieId+" Rating "+params.rating)
        FRUser user = FRUser.get(params.userId)
        Movie movie = Movie.get(params.movieId)
        if(user==null){
            System.out.println("user is null")
            render(template: "/templates/ratingwidget",model:[movie:movie, rating:0])
        }
        Rating rating = Rating.findByMovieAndUser(movie, user)
        if(rating!=null){

            rating.rating=Integer.parseInt(params.rating)
            rating.save(failOnError:true)
        } else{
            rating = new Rating(movie:movie, user:user, rating:Integer.parseInt(params.rating))
            rating.save(failOnError:true)
        }
        //Saves the rating action to the users activity feed
        ActivityFeedEvent event = new ActivityFeedEvent(user:user, movie:movie, action:"${user.username} rated ${movie.title} ${params.rating} stars on ${new Date().toTimestamp()}")
        event.save()
        render(template: "/templates/ratingwidget",model:[movie:movie, rating:params.rating])

    }
}
